package ua.javatrainer;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import java.security.Principal;
import java.util.ArrayList;


@Controller
public class MainPageController {
    @RequestMapping(value = "/", method= RequestMethod.GET)
    public ModelAndView getMainPage(){
        ModelAndView modelAndView = new ModelAndView("main");
        modelAndView.addObject("courses", getCourses());

        return modelAndView;
    }

    @RequestMapping(value = "/welcome", method = RequestMethod.GET)
    public String printWelcome(ModelMap model, Principal principal) {
        String name = principal.getName();
        model.addAttribute("username", name);
        model.addAttribute("message", "Spring Security Custom Form example");

        return "hello";
    }

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login() {
        return "login";
    }

    @RequestMapping(value = "/loginfailed", method = RequestMethod.GET)
    public String loginerror(ModelMap model) {
        model.addAttribute("error", "true");

        return "login";
    }

    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public String logout() {
        return "login";
    }

    private ArrayList<Course> getCourses() {
        ArrayList<Course> courses = new ArrayList<Course>();

        Course course = new Course();
        course.setName("Calculator");
        course.setDate("05-11-2013");

        ArrayList<Chapter> chapters = new ArrayList<Chapter>();
        Chapter chapter = new Chapter();
        chapter.setName("Input/Output");
        chapter.setText("This is first chapter");
        chapters.add(chapter);

        course.setChapters(chapters);

        courses.add(course);

        return courses;
    }
}
